#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
校园二手书交易平台 - Flask后端应用
作者：Inscode AI
创建时间：2025年12月
"""

import os
import json
import sqlite3
import hashlib
import secrets
from datetime import datetime, timedelta
from functools import wraps
from flask import Flask, request, jsonify, send_from_directory
from flask_cors import CORS
from werkzeug.security import generate_password_hash, check_password_hash

# 创建Flask应用
app = Flask(__name__)
app.config['SECRET_KEY'] = secrets.token_hex(32)
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024  # 16MB

# 启用CORS
CORS(app)

# 确保上传目录存在
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)

# 数据库文件路径
DATABASE = 'campus_book_market.db'

def get_db_connection():
    """获取数据库连接"""
    conn = sqlite3.connect(DATABASE)
    conn.row_factory = sqlite3.Row
    return conn

def init_database():
    """初始化数据库"""
    if not os.path.exists(DATABASE):
        print("正在初始化数据库...")
        with open('schema.sql', 'r', encoding='utf-8') as f:
            schema = f.read()
        
        conn = get_db_connection()
        conn.executescript(schema)
        conn.commit()
        conn.close()
        print("数据库初始化完成！")

def token_required(f):
    """JWT token验证装饰器"""
    @wraps(f)
    def decorated(*args, **kwargs):
        token = None
        
        if 'Authorization' in request.headers:
            auth_header = request.headers['Authorization']
            try:
                token = auth_header.split(' ')[1]  # Bearer <token>
            except IndexError:
                return jsonify({'success': False, 'message': 'Token格式错误'}), 401
        
        if not token:
            return jsonify({'success': False, 'message': 'Token缺失'}), 401
        
        try:
            # 简单的token验证（实际项目中应使用JWT）
            conn = get_db_connection()
            cursor = conn.cursor()
            cursor.execute('SELECT user_id, username FROM users WHERE token = ?', (token,))
            user = cursor.fetchone()
            conn.close()
            
            if not user:
                return jsonify({'success': False, 'message': 'Token无效'}), 401
            
            request.current_user = {
                'user_id': user['user_id'],
                'username': user['username']
            }
            
        except Exception as e:
            return jsonify({'success': False, 'message': f'Token验证失败: {str(e)}'}), 401
        
        return f(*args, **kwargs)
    
    return decorated

# ==================== 认证相关API ====================

@app.route('/api/auth/register', methods=['POST'])
def register():
    """用户注册"""
    try:
        data = request.get_json()
        
        # 验证必填字段
        required_fields = ['username', 'password', 'email', 'phone', 'student_number', 
                          'real_name', 'college', 'major', 'enrollment_year']
        
        for field in required_fields:
            if not data.get(field):
                return jsonify({
                    'success': False,
                    'message': f'{field}字段不能为空'
                }), 400
        
        conn = get_db_connection()
        cursor = conn.cursor()
        
        # 检查用户名是否已存在
        cursor.execute('SELECT user_id FROM users WHERE username = ?', (data['username'],))
        if cursor.fetchone():
            return jsonify({
                'success': False,
                'message': '用户名已存在'
            }), 400
        
        # 检查学号是否已存在
        cursor.execute('SELECT student_id FROM students WHERE student_number = ?', (data['student_number'],))
        if cursor.fetchone():
            return jsonify({
                'success': False,
                'message': '学号已存在'
            }), 400
        
        # 创建用户
        hashed_password = generate_password_hash(data['password'])
        token = secrets.token_hex(32)
        
        cursor.execute('''
            INSERT INTO users (username, password, email, phone, user_type, token)
            VALUES (?, ?, ?, ?, 'student', ?)
        ''', (data['username'], hashed_password, data['email'], data['phone'], token))
        
        user_id = cursor.lastrowid
        
        # 创建学生信息
        cursor.execute('''
            INSERT INTO students (user_id, student_number, real_name, college, major, enrollment_year)
            VALUES (?, ?, ?, ?, ?, ?)
        ''', (user_id, data['student_number'], data['real_name'], data['college'], 
              data['major'], data['enrollment_year']))
        
        conn.commit()
        conn.close()
        
        return jsonify({
            'success': True,
            'message': '注册成功',
            'token': token,
            'user': {
                'user_id': user_id,
                'username': data['username'],
                'user_type': 'student'
            }
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'注册失败: {str(e)}'
        }), 500

@app.route('/api/auth/login', methods=['POST'])
def login():
    """用户登录"""
    try:
        data = request.get_json()
        
        username = data.get('username')
        password = data.get('password')
        
        if not username or not password:
            return jsonify({
                'success': False,
                'message': '用户名和密码不能为空'
            }), 400
        
        conn = get_db_connection()
        cursor = conn.cursor()
        
        # 查找用户
        cursor.execute('SELECT user_id, username, password, user_type FROM users WHERE username = ?', (username,))
        user = cursor.fetchone()
        
        if not user or not check_password_hash(user['password'], password):
            return jsonify({
                'success': False,
                'message': '用户名或密码错误'
            }), 401
        
        # 生成新token
        token = secrets.token_hex(32)
        cursor.execute('UPDATE users SET token = ?, last_login = ? WHERE user_id = ?',
                      (token, datetime.now(), user['user_id']))
        
        # 记录登录历史
        cursor.execute('''
            INSERT INTO login_history (user_id, ip_address, user_agent)
            VALUES (?, ?, ?)
        ''', (user['user_id'], request.remote_addr, request.headers.get('User-Agent', '')))
        
        conn.commit()
        conn.close()
        
        return jsonify({
            'success': True,
            'message': '登录成功',
            'token': token,
            'user': {
                'user_id': user['user_id'],
                'username': user['username'],
                'user_type': user['user_type']
            }
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'登录失败: {str(e)}'
        }), 500

@app.route('/api/auth/verify', methods=['GET'])
@token_required
def verify_token():
    """验证token有效性"""
    return jsonify({
        'success': True,
        'user': request.current_user
    })

# ==================== 书籍相关API ====================

@app.route('/api/books', methods=['GET'])
def get_books():
    """获取书籍列表"""
    try:
        page = int(request.args.get('page', 1))
        limit = int(request.args.get('limit', 12))
        offset = (page - 1) * limit
        
        # 构建查询条件
        conditions = ['b.status = "active"']
        params = []
        
        # 搜索关键词
        keyword = request.args.get('keyword')
        if keyword:
            conditions.append('(b.title LIKE ? OR b.author LIKE ? OR b.isbn LIKE ?)')
            keyword_param = f'%{keyword}%'
            params.extend([keyword_param, keyword_param, keyword_param])
        
        # 学院筛选
        college = request.args.get('college')
        if college:
            conditions.append('b.college = ?')
            params.append(college)
        
        # 成色筛选
        condition = request.args.get('condition')
        if condition:
            conditions.append('b.condition = ?')
            params.append(condition)
        
        # 价格范围
        min_price = request.args.get('min_price')
        if min_price:
            conditions.append('b.price >= ?')
            params.append(float(min_price))
        
        max_price = request.args.get('max_price')
        if max_price:
            conditions.append('b.price <= ?')
            params.append(float(max_price))
        
        # 排序
        sort_by = request.args.get('sort_by', 'publish_time')
        sort_order = 'DESC' if sort_by == 'publish_time' else 'ASC'
        
        conn = get_db_connection()
        cursor = conn.cursor()
        
        # 获取总数
        count_query = f'''
            SELECT COUNT(*) as total
            FROM books b
            WHERE {' AND '.join(conditions)}
        '''
        cursor.execute(count_query, params)
        total = cursor.fetchone()['total']
        total_pages = (total + limit - 1) // limit
        
        # 获取书籍列表
        books_query = f'''
            SELECT b.*, u.username as seller_name, s.college as seller_college,
                   bi.image_path as primary_image, s.reputation as seller_reputation
            FROM books b
            JOIN users u ON b.seller_id = u.user_id
            JOIN students s ON u.user_id = s.user_id
            LEFT JOIN book_images bi ON b.book_id = bi.book_id AND bi.is_primary = 1
            WHERE {' AND '.join(conditions)}
            ORDER BY b.{sort_by} {sort_order}
            LIMIT ? OFFSET ?
        '''
        params.extend([limit, offset])
        
        cursor.execute(books_query, params)
        books = cursor.fetchall()
        
        conn.close()
        
        # 格式化书籍数据
        books_list = []
        for book in books:
            book_dict = dict(book)
            book_dict['publish_time'] = book_dict['publish_time']
            book_dict['update_time'] = book_dict['update_time']
            books_list.append(book_dict)
        
        return jsonify({
            'success': True,
            'books': books_list,
            'page': page,
            'total_pages': total_pages,
            'total': total
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取书籍列表失败: {str(e)}'
        }), 500

@app.route('/api/books/<int:book_id>', methods=['GET'])
def get_book_detail(book_id):
    """获取书籍详情"""
    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        
        # 获取书籍信息
        cursor.execute('''
            SELECT b.*, u.username as seller_name, s.college as seller_college, s.reputation as seller_reputation
            FROM books b
            JOIN users u ON b.seller_id = u.user_id
            JOIN students s ON u.user_id = s.user_id
            WHERE b.book_id = ?
        ''', (book_id,))
        
        book = cursor.fetchone()
        if not book:
            return jsonify({
                'success': False,
                'message': '书籍不存在'
            }), 404
        
        # 获取书籍图片
        cursor.execute('''
            SELECT image_path, thumbnail_path, is_primary
            FROM book_images
            WHERE book_id = ?
            ORDER BY sort_order
        ''', (book_id,))
        
        images = cursor.fetchall()
        
        # 获取收藏数
        cursor.execute('SELECT COUNT(*) as favorite_count FROM favorites WHERE book_id = ?', (book_id,))
        favorite_count = cursor.fetchone()['favorite_count']
        
        conn.close()
        
        book_dict = dict(book)
        book_dict['images'] = [img['image_path'] for img in images]
        book_dict['primary_image'] = next((img['image_path'] for img in images if img['is_primary']), None)
        book_dict['favorite_count'] = favorite_count
        
        return jsonify({
            'success': True,
            'book': book_dict
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取书籍详情失败: {str(e)}'
        }), 500

@app.route('/api/books', methods=['POST'])
@token_required
def create_book():
    """发布书籍"""
    try:
        # 检查用户类型
        if request.current_user['user_type'] != 'student':
            return jsonify({
                'success': False,
                'message': '只有学生用户可以发布书籍'
            }), 403
        
        # 获取表单数据
        title = request.form.get('title')
        isbn = request.form.get('isbn', '')
        author = request.form.get('author', '')
        publisher = request.form.get('publisher', '')
        condition = request.form.get('condition')
        price = float(request.form.get('price', 0))
        original_price = float(request.form.get('original_price', 0)) if request.form.get('original_price') else None
        category_id = int(request.form.get('category_id')) if request.form.get('category_id') else None
        college = request.form.get('college', '')
        course = request.form.get('course', '')
        description = request.form.get('description', '')
        
        # 验证必填字段
        if not title or not condition or price <= 0:
            return jsonify({
                'success': False,
                'message': '书名、成色和价格不能为空'
            }), 400
        
        conn = get_db_connection()
        cursor = conn.cursor()
        
        # 检查用户发布的书籍数量
        cursor.execute('SELECT COUNT(*) as count FROM books WHERE seller_id = ? AND status IN ("pending", "active")',
                      (request.current_user['user_id'],))
        book_count = cursor.fetchone()['count']
        
        if book_count >= 50:  # 最大发布数量限制
            return jsonify({
                'success': False,
                'message': '您发布的书籍数量已达上限'
            }), 400
        
        # 插入书籍记录
        cursor.execute('''
            INSERT INTO books (title, isbn, author, publisher, condition, price, original_price,
                             category_id, college, course, description, seller_id)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ''', (title, isbn, author, publisher, condition, price, original_price,
              category_id, college, course, description, request.current_user['user_id']))
        
        book_id = cursor.lastrowid
        
        # 处理图片上传
        images = request.files.getlist('images')
        for i, image in enumerate(images):
            if image and allowed_file(image.filename):
                filename = f"{book_id}_{i}_{secrets.token_hex(8)}.{image.filename.rsplit('.', 1)[1].lower()}"
                filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
                image.save(filepath)
                
                # 保存图片记录
                cursor.execute('''
                    INSERT INTO book_images (book_id, image_path, thumbnail_path, is_primary, sort_order)
                    VALUES (?, ?, ?, ?, ?)
                ''', (book_id, filename, filename, 1 if i == 0 else 0, i))
        
        conn.commit()
        conn.close()
        
        return jsonify({
            'success': True,
            'message': '书籍发布成功',
            'book_id': book_id
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'发布书籍失败: {str(e)}'
        }), 500

@app.route('/api/books/<int:book_id>/view', methods=['POST'])
def increment_book_view(book_id):
    """增加书籍浏览数"""
    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        
        cursor.execute('UPDATE books SET view_count = view_count + 1 WHERE book_id = ?', (book_id,))
        conn.commit()
        conn.close()
        
        return jsonify({
            'success': True,
            'message': '浏览数已更新'
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'更新浏览数失败: {str(e)}'
        }), 500

@app.route('/api/books/<int:book_id>/favorite', methods=['POST'])
@token_required
def favorite_book(book_id):
    """收藏书籍"""
    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        
        # 检查书籍是否存在
        cursor.execute('SELECT book_id FROM books WHERE book_id = ? AND status = "active"', (book_id,))
        if not cursor.fetchone():
            return jsonify({
                'success': False,
                'message': '书籍不存在或已下架'
            }), 404
        
        # 检查是否已收藏
        cursor.execute('SELECT favorite_id FROM favorites WHERE user_id = ? AND book_id = ?',
                      (request.current_user['user_id'], book_id))
        if cursor.fetchone():
            return jsonify({
                'success': False,
                'message': '已收藏过该书籍'
            }), 400
        
        # 添加收藏
        cursor.execute('INSERT INTO favorites (user_id, book_id) VALUES (?, ?)',
                      (request.current_user['user_id'], book_id))
        
        conn.commit()
        conn.close()
        
        return jsonify({
            'success': True,
            'message': '收藏成功'
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'收藏失败: {str(e)}'
        }), 500

@app.route('/api/books/categories', methods=['GET'])
def get_categories():
    """获取书籍分类"""
    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        
        cursor.execute('''
            SELECT category_id, name, parent_id, level
            FROM book_categories
            WHERE is_active = 1
            ORDER BY parent_id, sort_order, name
        ''')
        
        categories = cursor.fetchall()
        conn.close()
        
        return jsonify({
            'success': True,
            'categories': [dict(cat) for cat in categories]
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取分类失败: {str(e)}'
        }), 500

# ==================== 订单相关API ====================

@app.route('/api/orders', methods=['GET'])
@token_required
def get_orders():
    """获取用户订单"""
    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        
        cursor.execute('''
            SELECT o.*, 
                   b.title, b.condition, b.price,
                   buyer.username as buyer_name,
                   seller.username as seller_name
            FROM orders o
            JOIN books b ON o.book_id = b.book_id
            JOIN users buyer ON o.buyer_id = buyer.user_id
            JOIN users seller ON o.seller_id = seller.user_id
            WHERE o.buyer_id = ? OR o.seller_id = ?
            ORDER BY o.create_time DESC
        ''', (request.current_user['user_id'], request.current_user['user_id']))
        
        orders = cursor.fetchall()
        conn.close()
        
        orders_list = []
        for order in orders:
            order_dict = dict(order)
            order_dict['book_snapshot'] = json.loads(order_dict['book_snapshot'])
            orders_list.append(order_dict)
        
        return jsonify({
            'success': True,
            'orders': orders_list
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取订单失败: {str(e)}'
        }), 500

@app.route('/api/orders/<order_id>/accept', methods=['PUT'])
@token_required
def accept_order(order_id):
    """接受订单"""
    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        
        # 检查订单是否存在且属于当前用户
        cursor.execute('SELECT * FROM orders WHERE order_id = ? AND seller_id = ?',
                      (order_id, request.current_user['user_id']))
        order = cursor.fetchone()
        
        if not order:
            return jsonify({
                'success': False,
                'message': '订单不存在或无权限'
            }), 404
        
        if order['status'] != 'pending':
            return jsonify({
                'success': False,
                'message': '订单状态不正确'
            }), 400
        
        # 更新订单状态
        cursor.execute('UPDATE orders SET status = "accepted", update_time = ? WHERE order_id = ?',
                      (datetime.now(), order_id))
        
        # 记录状态变更历史
        cursor.execute('''
            INSERT INTO order_status_history (order_id, old_status, new_status, operator_id)
            VALUES (?, "pending", "accepted", ?)
        ''', (order_id, request.current_user['user_id']))
        
        conn.commit()
        conn.close()
        
        return jsonify({
            'success': True,
            'message': '订单已接受'
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'接受订单失败: {str(e)}'
        }), 500

@app.route('/api/orders/<order_id>/reject', methods=['PUT'])
@token_required
def reject_order(order_id):
    """拒绝订单"""
    try:
        data = request.get_json()
        reason = data.get('reason', '')
        
        conn = get_db_connection()
        cursor = conn.cursor()
        
        # 检查订单是否存在且属于当前用户
        cursor.execute('SELECT * FROM orders WHERE order_id = ? AND seller_id = ?',
                      (order_id, request.current_user['user_id']))
        order = cursor.fetchone()
        
        if not order:
            return jsonify({
                'success': False,
                'message': '订单不存在或无权限'
            }), 404
        
        if order['status'] != 'pending':
            return jsonify({
                'success': False,
                'message': '订单状态不正确'
            }), 400
        
        # 更新订单状态
        cursor.execute('UPDATE orders SET status = "rejected", seller_response = ?, update_time = ? WHERE order_id = ?',
                      (reason, datetime.now(), order_id))
        
        # 记录状态变更历史
        cursor.execute('''
            INSERT INTO order_status_history (order_id, old_status, new_status, operator_id, remark)
            VALUES (?, "pending", "rejected", ?, ?)
        ''', (order_id, request.current_user['user_id'], reason))
        
        conn.commit()
        conn.close()
        
        return jsonify({
            'success': True,
            'message': '订单已拒绝'
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'拒绝订单失败: {str(e)}'
        }), 500

@app.route('/api/orders/<order_id>/cancel', methods=['PUT'])
@token_required
def cancel_order(order_id):
    """取消订单"""
    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        
        # 检查订单是否存在且属于当前用户
        cursor.execute('SELECT * FROM orders WHERE order_id = ? AND buyer_id = ?',
                      (order_id, request.current_user['user_id']))
        order = cursor.fetchone()
        
        if not order:
            return jsonify({
                'success': False,
                'message': '订单不存在或无权限'
            }), 404
        
        if order['status'] != 'pending':
            return jsonify({
                'success': False,
                'message': '订单状态不正确'
            }), 400
        
        # 更新订单状态
        cursor.execute('UPDATE orders SET status = "cancelled", update_time = ? WHERE order_id = ?',
                      (datetime.now(), order_id))
        
        # 记录状态变更历史
        cursor.execute('''
            INSERT INTO order_status_history (order_id, old_status, new_status, operator_id)
            VALUES (?, "pending", "cancelled", ?)
        ''', (order_id, request.current_user['user_id']))
        
        conn.commit()
        conn.close()
        
        return jsonify({
            'success': True,
            'message': '订单已取消'
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'取消订单失败: {str(e)}'
        }), 500

@app.route('/api/orders/<order_id>/complete', methods=['PUT'])
@token_required
def complete_order(order_id):
    """完成订单"""
    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        
        # 检查订单是否存在且属于当前用户
        cursor.execute('SELECT * FROM orders WHERE order_id = ? AND buyer_id = ?',
                      (order_id, request.current_user['user_id']))
        order = cursor.fetchone()
        
        if not order:
            return jsonify({
                'success': False,
                'message': '订单不存在或无权限'
            }), 404
        
        if order['status'] != 'accepted':
            return jsonify({
                'success': False,
                'message': '订单状态不正确'
            }), 400
        
        # 更新订单状态
        cursor.execute('UPDATE orders SET status = "completed", complete_time = ?, update_time = ? WHERE order_id = ?',
                      (datetime.now(), datetime.now(), order_id))
        
        # 记录状态变更历史
        cursor.execute('''
            INSERT INTO order_status_history (order_id, old_status, new_status, operator_id)
            VALUES (?, "accepted", "completed", ?)
        ''', (order_id, request.current_user['user_id']))
        
        conn.commit()
        conn.close()
        
        return jsonify({
            'success': True,
            'message': '订单已完成'
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'完成订单失败: {str(e)}'
        }), 500

@app.route('/api/orders', methods=['POST'])
@token_required
def create_order():
    """创建订单"""
    try:
        data = request.get_json()
        
        book_id = data.get('book_id')
        buyer_message = data.get('buyer_message', '')
        
        if not book_id:
            return jsonify({
                'success': False,
                'message': '书籍ID不能为空'
            }), 400
        
        conn = get_db_connection()
        cursor = conn.cursor()
        
        # 检查书籍是否存在且可购买
        cursor.execute('SELECT * FROM books WHERE book_id = ? AND status = "active"', (book_id,))
        book = cursor.fetchone()
        
        if not book:
            return jsonify({
                'success': False,
                'message': '书籍不存在或已下架'
            }), 404
        
        # 不能购买自己的书籍
        if book['seller_id'] == request.current_user['user_id']:
            return jsonify({
                'success': False,
                'message': '不能购买自己发布的书籍'
            }), 400
        
        # 检查是否已有进行中的订单
        cursor.execute('''
            SELECT order_id FROM orders 
            WHERE book_id = ? AND buyer_id = ? AND status IN ("pending", "accepted")
        ''', (book_id, request.current_user['user_id']))
        
        if cursor.fetchone():
            return jsonify({
                'success': False,
                'message': '您已对该书籍下过订单'
            }), 400
        
        # 生成订单号
        order_id = f"ORD{datetime.now().strftime('%Y%m%d%H%M%S')}{secrets.token_hex(4).upper()}"
        
        # 创建订单快照
        book_snapshot = {
            'title': book['title'],
            'isbn': book['isbn'],
            'author': book['author'],
            'publisher': book['publisher'],
            'condition': book['condition'],
            'price': float(book['price']),
            'original_price': float(book['original_price']) if book['original_price'] else None,
            'description': book['description']
        }
        
        # 插入订单
        cursor.execute('''
            INSERT INTO orders (order_id, book_id, buyer_id, seller_id, book_snapshot, buyer_message)
            VALUES (?, ?, ?, ?, ?, ?)
        ''', (order_id, book_id, request.current_user['user_id'], book['seller_id'], 
              json.dumps(book_snapshot), buyer_message))
        
        conn.commit()
        conn.close()
        
        return jsonify({
            'success': True,
            'message': '订单创建成功',
            'order_id': order_id
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'创建订单失败: {str(e)}'
        }), 500

# ==================== 消息相关API ====================

@app.route('/api/messages', methods=['GET'])
@token_required
def get_messages():
    """获取用户消息"""
    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        
        cursor.execute('''
            SELECT m.*, 
                   sender.username as sender_name,
                   receiver.username as receiver_name
            FROM messages m
            JOIN users sender ON m.sender_id = sender.user_id
            JOIN users receiver ON m.receiver_id = receiver.user_id
            WHERE m.sender_id = ? OR m.receiver_id = ?
            ORDER BY m.create_time DESC
        ''', (request.current_user['user_id'], request.current_user['user_id']))
        
        messages = cursor.fetchall()
        conn.close()
        
        return jsonify({
            'success': True,
            'messages': [dict(msg) for msg in messages]
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取消息失败: {str(e)}'
        }), 500

@app.route('/api/messages', methods=['POST'])
@token_required
def send_message():
    """发送消息"""
    try:
        data = request.get_json()
        
        receiver_id = data.get('receiver_id')
        content = data.get('content')
        related_order_id = data.get('related_order_id')
        
        if not receiver_id or not content:
            return jsonify({
                'success': False,
                'message': '接收者和消息内容不能为空'
            }), 400
        
        conn = get_db_connection()
        cursor = conn.cursor()
        
        # 检查接收者是否存在
        cursor.execute('SELECT user_id FROM users WHERE user_id = ?', (receiver_id,))
        if not cursor.fetchone():
            return jsonify({
                'success': False,
                'message': '接收者不存在'
            }), 404
        
        # 插入消息
        cursor.execute('''
            INSERT INTO messages (sender_id, receiver_id, content, related_order_id)
            VALUES (?, ?, ?, ?)
        ''', (request.current_user['user_id'], receiver_id, content, related_order_id))
        
        conn.commit()
        conn.close()
        
        return jsonify({
            'success': True,
            'message': '消息发送成功'
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'发送消息失败: {str(e)}'
        }), 500

# ==================== 工具函数 ====================

def allowed_file(filename):
    """检查文件类型是否允许"""
    ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

# ==================== 静态文件服务 ====================

@app.route('/uploads/<filename>')
def uploaded_file(filename):
    """提供上传的文件"""
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)

@app.route('/')
def index():
    """提供前端页面"""
    return send_from_directory('../frontend', 'index.html')

@app.route('/<path:filename>')
def static_files(filename):
    """提供静态文件"""
    return send_from_directory('../frontend', filename)

# ==================== 主程序 ====================

if __name__ == '__main__':
    # 初始化数据库
    init_database()
    
    # 启动应用
    print("校园二手书交易平台后端服务启动...")
    print("API文档：http://localhost:5000/api")
    print("前端页面：http://localhost:5000")
    
    app.run(debug=True, host='0.0.0.0', port=5000)
